/**
 * Created by charlesl on 2017/6/21.
 */
import 'whatwg-fetch'
import Cookies from 'js-cookie'

function parseJSON(response) {
  return response.json()
}
function genParamStr(obj) {
  let paramsArr = []
  for (let prop in obj) {
    paramsArr.push(`${prop}=${obj[prop]}`)
  }
  return paramsArr.join('&')
}

function checkStatus(response) {
  if (response.status === 201 || response.status === 204) {
    return response
  }
  if (response.status >= 200 && response.status < 300) {
    return parseJSON(response)
  }

  const error = new Error(response.statusText)
  error.response = response
  throw error
}

function request(url, options) {
  return fetch(url, options)
    .then(checkStatus)
}
export function get(url, params) {
  if (typeof params === 'undefined') {
    return request(url)
  } else {
    let paramStr
    if (typeof params === 'object') {
      paramStr = genParamStr(params)
    } else {
      paramStr = params
    }
    return request(`${url}?${paramStr}`)
  }
}
export function post(url, body, config) {
  let defaultConfig = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/x-www-form-urlencoded',
      'authorization': 'Bearer ' + Cookies.get('token')
    },
    mode: 'cors',
    cache: 'default',
    body: genParamStr(body)
  }
  console.log(config)
  let _config = Object.assign({}, defaultConfig, config)
  return request(url, _config)
}
function postJson(url, body, config) {
  let defaultConfig = {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'authorization': 'Bearer ' + Cookies.get('token')
    },
    mode: 'cors',
    cache: 'default',
    body: JSON.stringify(body)
  }
  let _config = Object.assign({}, defaultConfig, config)
  return request(url, _config)
}
function put(url, body, config) {
  return post(url, body, Object.assign({ method: 'PUT' }, config))
}

export default {
  get,
  post,
  put,
  postJson
}
